<?php
class MPublisher {
    public static $published = array();
    
    /**
     * Publish a file (or a directory) to the 'public' accessible directory.
     * @param String $path : The absolute path of the file (or directory) to publish
     * @param Booleand $autoImport : A boolean to auto import the file in the template
     * @return String||Boolean : The relative path to the copied file. Boolean if it was a directory
     */
    public static function publish($path, $autoImport = false){
        if (isset (self::$published[$path])){
            return self::$published[$path];
        } else if (file_exists($path)) {
            $request = new MRequest();
            $router = MRouter::getInstance();
            $router->getRoute($request);
            $moduleClass = MNormalizer::normalizeModuleClass($request->getModule());
            $dir = ABS_PUBLIC_PATH.DS.self::hash($request->getModule().$moduleClass::getVersion());
            $relDir = REL_PUBLIC_PATH.'/'.self::hash($request->getModule().$moduleClass::getVersion());
            if (is_file($path)){
                $destFile = $dir.DS.basename($path);
                if(@filemtime($destFile)<@filemtime($path)){
                    if (!is_dir($dir)){
                        mkdir($dir);
                        @chmod($dir, 0777);
                    }
                    copy($path, $destFile);
                }
                $relPath = $relDir.'/'.basename($path);
                if ($autoImport){
                    $ext = MFile::getExtension($path);
                    switch ($ext) {
                        case 'css':
                            MTemplate::getInstance()->addStylesheet($relPath);
                            break;
                        case 'js':
                            MTemplate::getInstance()->addScript($relPath);
                            break;
                        default:
                            break;
                    }
                }
                return self::$published[$path] = $relPath;
            } else if (is_dir($path)){
                MFile::copyDirectory($path, $dir);
                return true;
            }
        } else 
            throw new MException (__t('mandrill.web.publisher.pathNotExists', array('path'=>$path)));
    }
    
    /**
     * Generates a hash for the specified path.
     * @param String $text : The text to hash
     * @return String : The generated Hash 
     */
    public static function hash($text){
        return sprintf('%x', crc32($text));
    }
}
?>
